#
# Makefile to build the remote protocol
#

# Main target
#   anymote:     creates a jar containing the protocol
#   anymoteJava: compiles the java sources
#   proto:       compiles the protocol buffers

.PHONY: proto anymote anymoteJava clean cleanProto default

default: anymote

###############
# DEFINITIONS #
###############
# Sources top directory
JAVA_SRC_TOP := src

# Package name
PACKAGE_NAME := com/google/anymote

# Complete path to sources
JAVA_SRC_DIR := $(JAVA_SRC_TOP)/$(PACKAGE_NAME)

# Java sources
JAVA_SRC := $(JAVA_SRC_DIR)/common/*.java \
	    $(JAVA_SRC_DIR)/device/*.java \
	    $(JAVA_SRC_DIR)/server/*.java 

# .class targets
JAVA_SRC_CLASSES = $(patsubst %.java,%.class,$(wildcard $(JAVA_SRC)))

# Classpath 
JAVA_CLASSPATH := $(subst jar ,jar:,$(strip "bin:$(wildcard jar/*.jar)"))

# Location to put the generated .class
JAVA_OUT := bin

# Name for the jar that will be created
JAR_NAME := anymote.jar

####################
# PROTOCOL BUFFERS #
####################
# Sources directory for protocols buffers
PROTO_SRC_DIR := ../proto

# Location for the java files generated by the proto compiler
PROTO_JAVA_OUT := proto_out

# Creates the needed directories
$(PROTO_JAVA_OUT) $(JAVA_OUT):
	-mkdir -p $@

# Definition of the .proto and the corresponding java generated files.
$(PROTO_JAVA_OUT)/$(PACKAGE_NAME)/RemoteProto.java: $(PROTO_SRC_DIR)/remote.proto
	$(genproto)

$(PROTO_JAVA_OUT)/$(PACKAGE_NAME)/Codes.java: $(PROTO_SRC_DIR)/keycodes.proto
	$(genproto)

# All java files generated from proto.
ALL_GENPROTOS := \
	$(PROTO_JAVA_OUT)/$(PACKAGE_NAME)/RemoteProto.java \
	$(PROTO_JAVA_OUT)/$(PACKAGE_NAME)/Codes.java

# Rule to build a .proto in the proto/ directory
define genproto
	protoc \
	  --java_out=$(PROTO_JAVA_OUT) \
	  -I $(PROTO_SRC_DIR) \
	  $<
endef

# Compiles the proto
proto: $(PROTO_JAVA_OUT) $(ALL_GENPROTOS)

#################
# JAVA COMPILER #
#################
# compiles a java source
%.class: %.java
	javac \
	  -sourcepath "$(JAVA_SRC_TOP):$(PROTO_JAVA_OUT)" \
	  -classpath $(JAVA_CLASSPATH) \
	  -d $(JAVA_OUT)/ \
	  $?

#################
# PROJECT RULES #
#################
# Compiles the java sources for the project
anymoteJava: $(JAVA_OUT) proto $(JAVA_SRC_CLASSES)

# Cleans the generated protocol buffers
cleanProto:
	-rm -rf $(PROTO_JAVA_OUT)

# Cleans the project
clean: cleanProto
	-rm -rf $(JAVA_OUT)
	-rm $(JAR_NAME)

# Complete and clean build of the project returns a jar.
anymote: clean anymoteJava
	jar cf $(JAR_NAME) -C $(JAVA_OUT) $(shell ls $(JAVA_OUT))
